﻿var WindowModel = new Object();
function WorkWithClassif() {
    WindowModel.FullName = $('#itemFullName').attr('value');
    WindowModel.Name = $('#itemName').attr('value');
    WindowModel.Id = $('#itemId').attr('value');
    $.ajax({
        url: '/data/Classificator',
        type: WindowModel.Type,
        data: WindowModel,
        success: function (data) {
            data.label = data.id + " " + data.label;
            if (WindowModel.Type == "POST") {
                $('#jqxTree').jqxTree('addTo', data, $('#jqxTree').jqxTree('selectedItem').element);
            } else {
                var q = $('#jqxTree').jqxTree('selectedItem').parentElement;
                $('#jqxTree').jqxTree('removeItem', $('#jqxTree').jqxTree('selectedItem').element);
                $('#jqxTree').jqxTree('addTo', data, q);
            }
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });
};
function DeleteClassif() {
    $.ajax({
        url: '/data/Classificator/' + WindowModel.Id,
        type: "DELETE",
        //data: { id: WindowModel.Id },
        success: function (data) {
            $('#jqxTree').jqxTree('removeItem', $('#jqxTree').jqxTree('selectedItem').element);
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });
};
$(document).ready(function () {
    //инициализация окна редактирования
    $('#mainSplitter').jqxSplitter({ width: '100%', height: '100%', theme: theme, panels: [{ size: '30%' }] });

    $('#AddEditWindow').jqxWindow({
        width: '300',height: '220',resizable: false,
        isModal: true,autoOpen: false, theme: theme,
        cancelButton: $('#cancelButton'),
        okButton: $('#okButton'),
        initContent: function () {
            $('#AddEditWindow').jqxWindow({ title: WindowModel.Title });
            
            $("#itemId").jqxInput({
                placeHolder: "Индификатор", height: 25, width: '100%',
                minLength: 1, theme: theme
            });
            $('#itemId').attr('value', WindowModel.Id);
            $("#itemName").jqxInput({
                placeHolder: "Краткое название", height: 25, width: '100%',
                minLength: 1, theme: theme
            });
            $('#itemName').attr('value', WindowModel.Name);
            $("#itemFullName").jqxInput({
                placeHolder: "Полное название", height: 25,
                width: '100%', minLength: 1, theme: theme
            });

            $('#itemFullName').attr('value', WindowModel.FullName);
            $("#cancelButton").jqxButton({ width: '100', theme: theme });
            $("#okButton").jqxButton({ width: '100', theme: theme });

        }
    });



    //инициализация окна удаления
    $('#DeleteWindow').jqxWindow({
        width: 410,height: 140,resizable: false,
        isModal: true, theme: theme,autoOpen: false,
        cancelButton: $('#cancelButton'),
        okButton: $('#okButton'),
        initContent: function () {
            $('#DeleteWindow').jqxWindow({ title: ("Удаление узла " + WindowModel.FullName) });
            $("[type=button]").jqxButton({ width: '100', theme: theme });
        }
    });

    var tree = $('#jqxTree');
    //первая загрузка
    $.ajax({
        url: '/data/Classificator',
        type: "GET",
        contentType :'application/json; charset=UTF-8',
        dataType: "json",
        success: function (data) {
            for (var curId in data) {
                data[curId].label = data[curId].id + " " + data[curId].label;
            }
            // Create jqxTree
            tree.jqxTree({ height: '100%', width: '100%', source: data, animationShowDuration: 0, allowDrag: false });
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });

    var clickedItem = null;
    //Create context menu
    var contextMenu = $("#jqxMenu").jqxMenu({
        width: '120px',
        height: '84px',
        autoOpenPopup: false,
        mode: 'popup'
    });
    // open the context menu when the user presses the mouse right button.
    $("#jqxTree li").live('mousedown', function (event) {
        var target = $(event.target).parents('li:first')[0];
        
        var rightClick = isRightClick(event);
        if (rightClick && target != null) {
            tree.jqxTree('selectItem', target);
            var scrollTop = $(window).scrollTop();
            var scrollLeft = $(window).scrollLeft();
            contextMenu.jqxMenu('open', parseInt(event.clientX) + 5 + scrollLeft, parseInt(event.clientY) + 5 + scrollTop);
            return false;
        }
    });

    //биндинг на дозагрузку    
    tree.bind('expand', function (event) {
        var $element = $(event.args.element);
        var loader = false;
        var loaderItem = null;
        var children = $element.find('li');
        $.each(children, function () {
            var item = tree.jqxTree('getItem', this);
            if (item.label == 'Loading...') {
                loaderItem = item;
                loader = true;
                return false;
            }
            ;
        });
        if (loader) {
            $.ajax({
                url: '/data/Classificator',
                data: { id: loaderItem.value },
                contentType :'application/json; charset=UTF-8',
                dataType: "json",
                success: function (data, status, xhr) {
                    if (data.length > 0) {
                        for (var curId in data) {
                            data[curId].label = data[curId].id + " " + data[curId].label;
                        }
                        tree.jqxTree('addTo', data, $element[0]);
                        tree.jqxTree('removeItem', loaderItem.element);
                    } else {
                        tree.jqxTree('removeItem', loaderItem.element);
                    }
                },
                error: function () {
                    alert("Не удалось подключиться к серверу");
                }
            });
        }
    });

    tree.bind('select', function (event) {
        var id = $('#jqxTree').jqxTree('selectedItem').element.id;
        $.ajax({
            url: '/Administration/Classificator',
            type: "POST",
            data: { id: id },
            dataType: "html",
            success: function (data) {
                $("#MainContent").html(data);
            },
            error: function () {
                alert('Невозможно подключиться к серверу данных.');
            }
        });
    });
    //биндинг меню
    $("#jqxMenu").bind('itemclick', function (event) {
        var item = $(event.args).attr("name");
        switch (item) {
            case "AddItem":
                var selectedItem = $('#jqxTree').jqxTree('selectedItem');
                if (selectedItem != null) {
                    WindowModel.Id = "";
                    WindowModel.MasterId = selectedItem.id;
                    WindowModel.Title = 'Добавить';
                    WindowModel.Name = 'Новый';
                    WindowModel.Type = "POST";
                    WindowModel.FullName = 'Новый элемент';
                    $('#AddEditWindow').jqxWindow('open');
                }
                break;
            case "UpdateItem":
                var selectedItem = $('#jqxTree').jqxTree('selectedItem');
                if (selectedItem != null) {
                    WindowModel.Id = selectedItem.id;
                    WindowModel.MasterId = selectedItem.parentId;
                    if (WindowModel.MasterId == 0) WindowModel.MasterId = null;
                    WindowModel.Title = 'Изменить';
                    WindowModel.Type = "PUT";
                    WindowModel.FullName = selectedItem.label.replace(selectedItem.id + " ", "");
                    WindowModel.Name = selectedItem.value;
                    $('#AddEditWindow').jqxWindow('open');
                    // $('#jqxTree').jqxTree('removeItem', selectedItem.element);
                }
                break;
            case "RemoveItem":
                var selectedItem = $('#jqxTree').jqxTree('selectedItem');
                if (selectedItem != null) {
                    WindowModel.FullName = selectedItem.label;
                    WindowModel.Id = selectedItem.id;
                    $('#DeleteWindow').jqxWindow('open');
                }
                break;

        }
    });

    // disable the default browser's context menu.
    $('#mainSplitter').bind('contextmenu', function (e) {
        if ($(e.target).parents('.jqx-tree').length > 0) {
            return false;
        }
        return true;
    });

    function isRightClick(event) {
        var rightclick;
        if (!event) var event = window.event;
        if (event.which) rightclick = (event.which == 3);
        else if (event.button) rightclick = (event.button == 2);
        return rightclick;
    }


});

